<script>
	import gallery from "$lib/shared/components/chat/gallery.svelte";
	import { onMount } from "svelte";
	import mermaid from "mermaid";
	import html2canvas from "html2canvas";
	import { goto } from "$app/navigation";

	let diagram; // Mermaid 图的代码
	let container; // 右侧显示区域
	
	onMount(async () => {
		try {
			// 从 sessionStorage 获取 diagram 的值
			const value = sessionStorage.getItem("msg_key");
			if (value) {
				try {
					// 将 b'' 表示的字节字符串拼接还原为普通字符串
					const decodedValue = value
						.replace(/b'/g, "") // 去掉 b' 前缀
						.replace(/'/g, "") // 去掉单引号
						.replace(/\\n/g, "\n"); // 替换换行符

					// 使用正则提取 ```mermaid 和 ``` 之间的内容
					const match = decodedValue.match(/```mermaid([\s\S]*?)```/);
					if (match && match[1]) {
						diagram = match[1].trim(); // 提取并去除首尾空白
						console.log("Diagram:", diagram);
					} else {
						console.warn("No Mermaid content found.");
					}
				} catch (error) {
					console.error("Error processing value:", error);
				}
			} else {
				// 如果没有 msg_key，则使用默认值
				diagram = `graph TD
                        A[客户申请] --> B[审批]
                        A --> C[信用检查]
                        B -->|通过| D[贷款批准]
                        B -->|未通过| E[贷款拒绝]
                        C -->|通过| D
                        C -->|未通过| F[提供更多信息]
                        F --> C`;
			}

			// 渲染初始图表
			await updateDiagram();
		} catch (err) {
			console.error("Mermaid render error:", err);
		}
	});

	// 更新并重新渲染 Mermaid 图表
	const updateDiagram = async () => {
		try {
			// Mermaid 渲染图表
			const { svg } = await mermaid.render("mermaid", diagram);
			container.innerHTML = svg; // 将生成的 SVG 添加到右侧容器中
		} catch (err) {
			console.error("Mermaid render error:", err);
		}
	};

	// 将图表保存为图片
	const saveDiagramAsImage = async () => {
		try {
			html2canvas(container).then((canvas) => {
				canvas.toBlob((blob) => {
					const link = document.createElement("a");
					link.href = URL.createObjectURL(blob);
					link.download = "diagram.png";
					link.click();
				});
			});
		} catch (err) {
			console.error("Error rendering with html2canvas:", err);
		}
	};
</script>

<main class="flex h-full">
	<!-- Sidebar -->
	<div class="sidebar fixed left-0 top-0 h-full w-64 bg-[#bfc4da] text-white">
		<div class="p-4">
			<h2 class="mb-6 text-2xl font-bold">Sidebar</h2>
			<ul class="space-y-4">
				<li>
					<button
						on:click={() => goto("/mermaid")}
						class="w-full rounded-lg bg-[#654e72] px-4 py-2 text-left text-lg font-semibold transition-all duration-200 ease-in-out hover:bg-[#c7bdd6] focus:bg-gray-600 active:bg-[#c7bdd6]"
					>
						Go to Mermaid
					</button>
				</li>
				<li>
					<button
						on:click={() => goto("/drawer")}
						class="w-full rounded-lg bg-[#654e72] px-4 py-2 text-left text-lg font-semibold transition-all duration-200 ease-in-out hover:bg-[#c7bdd6] focus:bg-gray-600 active:bg-[#c7bdd6]"
					>
						Go to Drawer
					</button>
				</li>
				<li>
					<button
						on:click={() => goto("/project")}
						class="w-full rounded-lg bg-[#654e72] px-4 py-2 text-left text-lg font-semibold transition-all duration-200 ease-in-out hover:bg-[#c7bdd6] focus:bg-gray-600 active:bg-[#c7bdd6]"
					>
						Go to Project
					</button>
				</li>
			</ul>
		</div>
	</div>
	<!-- Main content -->
	<div
		class="main-content ml-64 flex flex-1 flex-col p-4"
		style="font-size=2rem;"
	>
		<div class="flex h-full rounded-lg bg-white">
			<!-- 左侧区域 -->
			<div class="left flex-1 border-r border-gray-300 p-4">
				<div class="flex flex-col gap-4">
					<div class="flex justify-between p-2">
						<p class="text-[1.7rem] font-bold tracking-tight text-[#6c80a9]">Mermaid Code</p>
					</div>
					<div class="mt-4">
						<pre
							contenteditable="true"
							class="w-full rounded-md border border-[#b1a9da] p-2"
							bind:innerHTML={diagram}
							on:input={(event) => {
								diagram = event.target.innerText;
								updateDiagram();
							}}
						/>
					</div>
				</div>
			</div>

			<!-- 右侧区域 -->
			<div class="right flex-1 p-4">
				<div class="flex h-full flex-col gap-4">
					<div class="flex justify-between p-2">
						<p class="text-[1.7rem] font-bold tracking-tight text-[#6c80a9]">Diagram Viewer</p>
					</div>
					<div class="flex h-full flex-col gap-2 overflow-auto">
						<span bind:this={container} />
					</div>
				</div>
			</div>
		</div>

		<div class="button-group">
			<button on:click={updateDiagram}>Update Diagram</button>
			<button on:click={saveDiagramAsImage}>Save as Image</button>
		</div>
	</div>
</main>

<style>
	pre {
		width: 100%;
		height: 300px;
		overflow-y: auto;
		padding: 10px;
		background: #f9f9f9;
		border: 1px solid #ddd;
	}

	span {
		display: block;
		margin-top: 20px;
		border: 1px solid #ddd;
		padding: 20px;
		background-color: #f1f1f1;
		min-height: 350px;
	}

	button {
		background-color: #654e72;
		color: white;
		padding: 10px 20px;
		margin-right: 50px;
		border: none;
		border-radius: 5px;
		cursor: pointer;
	}

	button:hover {
		background-color: #c7bdd6;
	}

	.main-content {
		margin-left: 264px;
		padding: 16px;
		height: 100%;
		overflow: auto;
	}

	.button-group {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
</style>
